package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordColData;
import com.iqiyi.pps.epg.api.model.web.record.TRecordColDataPage;
import com.iqiyi.pps.epg.api.server.web.record.RecordColRpcService;
import com.iqiyi.pps.epg.api.utils.ApiHttpRequestUtil;
import com.iqiyi.pps.epg.api.utils.Constants;
import com.iqiyi.pps.epg.api.utils.ServiceUtil;
import com.iqiyi.pps.epg.api.utils.puyu.HttpSignatureUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangle on 2018/4/11.
 */
@Service
public class RecordColProxy extends BaseProxy {

    private static Logger logger = LoggerFactory.getLogger(RecordColProxy.class);

    /**
     * 保存收录栏目记录
     *
     * @param data
     * @return
     */
    public String saveRecordColData(String data) {
        try {
            if (StringUtils.isEmpty(data)) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            RecordColRpcService.Iface service = getRecordColRpcService();
            String opUser = ServiceUtil.getOpUser();
            JSONObject jsonObject = JSON.parseObject(data);
            jsonObject.put("opUser", opUser);
            String result = service.save(jsonObject.toJSONString());
            logger.info("[RecordColProxy][saveRecordColData][data=" + data + "]");
            return Constants.getJsonResponse(result, null, Constants.getCode(result));
        } catch (Exception e) {
            logger.error("[RecordColProxy][saveRecordColData][data=" + data + "]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    /**
     * 更新收录栏目记录
     *
     * @param data
     * @return
     */
    public String updateRecordColData(String data) {
        try {
            if (StringUtils.isEmpty(data)) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            RecordColRpcService.Iface service = getRecordColRpcService();
            String opUser = ServiceUtil.getOpUser();
            JSONObject jsonObject = JSON.parseObject(data);
            jsonObject.put("opUser", opUser);
            String result = service.update(jsonObject.toJSONString());
            logger.info("[RecordColProxy][updateRecordColData][data=" + data + "]");
            return Constants.getJsonResponse(result, null, Constants.getCode(result));
        } catch (Exception e) {
            logger.error("[RecordColProxy][updateRecordColData][data=" + data + "]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    public String getAutoNewDataList(Integer pageSize, Integer pageNo, String paramsObj) {
        try {
            RecordColRpcService.Iface service = getRecordColRpcService();
            if (pageNo == null) {
                pageNo = 1;
            }
            if (pageSize == null) {
                pageSize = 20;
            }
            Map<String, String> params = new HashMap<>();
            if (paramsObj != null) {
                JSONObject jsonObject = JSONObject.parseObject(paramsObj);
                for (Map.Entry<String, Object> temp : jsonObject.entrySet()) {
                    params.put(temp.getKey(), temp.getValue() + "");
                }
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "createTime", "desc", true);
            TRecordColDataPage dataPage = service.getRecordCol(page, tFilter);
            if (dataPage != null) {
                return Constants.getResponse(Constants.CODE_SUC, dataPage, "操作成功").toJsonString();
            } else {
                return Constants.getJsonResponse(Constants.CODE_ERROR, null, PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getAutoNewDataList]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }


    /**
     * 删除收录栏目的数据
     *
     * @param id
     * @return
     */
    public String deleteRecordColData(Long id) {
        try {
            logger.info("[RecordColProxy][deleteRecordColData][start][id=" + id + "]");
            if (id == null) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            RecordColRpcService.Iface service = getRecordColRpcService();
            String result = service.deleteRecordCol(id);
            logger.info("[RecordColProxy][deleteRecordColData][finish][id=" + id + "]");
            return Constants.getJsonResponse(result, null, Constants.getCode(result));
        } catch (Exception e) {
            logger.error("[RecordColProxy][deleteRecordColData][error][id=" + id + "]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    /**
     * 栏目信息
     *
     * @param id
     * @return
     */
    public String getRecordColInfo(Long id) {
        try {
            logger.info("[RecordColProxy][getRecordColInfo][start][id=" + id + "]");
            if (id == null) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            RecordColRpcService.Iface service = getRecordColRpcService();
            TRecordColData recordColInfo = service.getRecordColInfo(id);
            logger.info("[RecordColProxy][getRecordColInfo][finish][id=" + id + "]");
            return Constants.getResponse(Constants.CODE_SUC, recordColInfo,"操作成功").toJsonString();
        } catch (Exception e) {
            logger.error("[RecordColProxy][getRecordColInfo][error][id=" + id + "]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    public static String authList(String name, String currentPage){
        try{
            String key ="317A4902FD3775103246E61CE6AE54AE3425B6323440FD32";
            String clientId = "7";
            Map<String, Object> pp = new HashMap();
            pp.put("cprVideoName", URLEncoder.encode(name,"utf-8"));
            pp.put("currentPage", currentPage);
            pp.put("pageSize",10);
            //pp.put("showAll",0);
            Long ts = System.currentTimeMillis();
            pp.put("ts",ts);
            String auth = HttpSignatureUtil.createToken(clientId, key, pp);
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("CPR-Authentication",auth);
            Map<String, String> req = new HashMap<String, String>();
            for (Map.Entry<String, Object> entry : pp.entrySet()){
                req.put(entry.getKey(), entry.getValue().toString());
            }
            String query = HttpSignatureUtil.join(pp);
            String url = "http://test.cpr.qiyi.domain/cprInter/findAllCprListV2.action?" +query;
            String res = ApiHttpRequestUtil.getMethod(url, headers, req);
            return res;
        }catch (Exception e){
            logger.error("[RecordColProxy][authList][error][cprName=" + name + "]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }

    }

}
